<template>
	<cl-drawer
		ref="drawer"
		:props="{
			title: '快速新增',
			size: '750px',
			appendToBody: true
		}"
		show-confirm
		confirm-text="提交"
		@confirm="submit"
		@close="reset"
		:saving="saving"
	>
		<el-form ref="form" :model="form" :rules="rules" label-position="top" :disabled="saving">
			<el-card shadow="never">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="事业部" prop="biz_id">
							<cl-select
								v-model="form.biz_id"
								style="width: 100%"
								filterable
								@change="changeBiz"
								:disabled="haveFan"
							>
								<el-option
									v-for="item in business"
									:key="item.biz_id"
									:label="item.biz_name"
									:value="item.biz_id"
								/>
							</cl-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
							<el-form-item label="分公司" prop="company_id">
								<cl-select
									v-model="form.company_id"
									placeholder="请选择分公司"
									style="width: 100%"
									filterable
								>
									<el-option
										:label="item.company_name"
										:value="item.company_id"
										v-for="(item, index) in companyList"
										:key="index"
									/>
								</cl-select>
							</el-form-item>
						</el-col> -->
					<el-col :span="12">
						<el-form-item ref="brand" label="品牌" prop="bra_id">
							<cl-select
								v-model="form.bra_id"
								placeholder="请选择品牌"
								style="width: 100%"
								filterable
								@change="changeBra"
							>
								<el-option
									:label="item.bra_name"
									:value="item.bra_id"
									v-for="(item, index) in bizRefData.brand"
									:key="index"
								/>
							</cl-select>
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="userInfo.dept_post == 2">
						<el-form-item label="老客户" prop="cus_type">
							<cl-select
								v-model="form.cus_type"
								placeholder="请选择"
								style="width: 100%"
								filterable
							>
								<el-option label="否" :value="0" />
								<el-option label="是" :value="2" />
							</cl-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="userInfo.dept_post == 2 && form.cus_type == 2">
						<el-form-item label="首次到店" prop="first_shop">
							<cl-date-picker
								v-model="form.first_shop"
								placeholder="选择日期"
								value-format="yyyy-MM-dd"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12" v-if="userInfo.dept_post == 2 && form.cus_type == 2">
						<el-form-item label="到店次数" prop="to_shop">
							<el-input
								v-model.trim="form.to_shop"
								type="number"
								class="clear-number-input"
								placeholder="请填写到店次数"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="客户姓名" prop="cus_name">
							<el-input
								v-model="form.cus_name"
								placeholder="请填写客户姓名"
								maxlength="30"
								:disabled="haveFan"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item
							prop="cus_mobile"
							:required="form.has_appoint == 1 || requiredFields.cus_mobile"
							:rules="rules.cus_mobile"
						>
							<div slot="label" style="display: inline-block">
								手机号
								<span class="tips" v-if="!hideFields.has_appoint">
									(有预约时项目必填)
								</span>
							</div>
							<el-input
								v-model="form.cus_mobile"
								maxlength="11"
								placeholder="请填写手机号"
								@blur="() => validField('cus_mobile')"
								:disabled="haveFan"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="微信号" prop="cus_wx">
							<el-input
								v-model.trim="form.cus_wx"
								placeholder="请填写微信号"
								maxlength="20"
								@input="cusWxChange"
								:disabled="haveFan"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="会员性别" prop="cus_sex" required>
							<cl-select
								v-model="form.cus_sex"
								placeholder="请选择"
								style="width: 100%"
							>
								<el-option label="女" :value="2" />
								<el-option label="男" :value="1" />
							</cl-select>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item
							ref="wechatJoinDay"
							prop="wechat_join_day"
							:required="!!form.cus_wx"
						>
							<div slot="label" style="display: inline-block">
								加微时间
								<span class="tips">(用于每日加微统计)</span>
							</div>
							<cl-date-picker
								v-model="form.wechat_join_day"
								:picker-options="pickerOptions"
								placeholder="选择日期"
								value-format="yyyy-MM-dd"
								style="width: 100%"
							/>
						</el-form-item>
					</el-col>

					<el-col :span="12">
						<el-form-item label="加微方式" prop="id_join_type">
							<cl-select
								v-model="form.id_join_type"
								placeholder="请选择加微方式"
								style="width: 100%"
							>
								<el-option
									v-for="(item, index) in $const.WX_JOIN_TYPE"
									:key="index"
									:label="item.label"
									:value="item.value"
								/>
							</cl-select>
						</el-form-item>
					</el-col>
					<el-col :span="12" v-if="form.id_join_type == 5">
						<el-form-item prop="addWechatNumber">
							<div slot="label" style="display: inline-block">
								企业微信码
								<span class="tips">(加微方式为企业微信码时选择)</span>
							</div>
							<cl-select
								v-model="form.addWechatNumber"
								placeholder="请选择企业微信码"
								style="width: 100%"
							>
								<el-option
									v-for="(item, index) in enterpriseWxList"
									:key="index"
									:label="item.label"
									:value="item.label"
								/>
							</cl-select>
						</el-form-item>
					</el-col>
					<template v-if="form.id_join_type == 99">
						<el-col :span="12">
							<el-form-item prop="source_id">
								<div slot="label" style="display: inline-block">
									来源渠道
									<span class="tips">(加微方式为其他时选择)</span>
								</div>
								<cl-select
									v-model="form.source_id"
									placeholder="请选择来源渠道"
									style="width: 100%"
								>
									<el-option
										v-for="(item, index) in sourceList"
										:key="index"
										:label="item.cname"
										:value="item.id"
									/>
								</cl-select>
							</el-form-item>
						</el-col>
						<el-col :span="12" v-if="form.source_id == 798">
							<el-form-item label="来源会员号" prop="from_cus_id">
								<el-input
									v-model.trim="form.from_cus_id"
									placeholder="请填写介绍人会员号"
								/>
							</el-form-item>
						</el-col>
					</template>
				</el-row>
			</el-card>
		</el-form>
	</cl-drawer>
</template>
<script>
import dayjs from "dayjs";
import { validate } from "@/utils/validate";
export default {
	name: "cl-customer-form",
	inject: ["$layout"],
	data() {
		// 手机号
		const mobileValidator = (rule, value, callback) => {
			const { has_appoint } = this.form;
			const { requiredFields } = this;
			if (!has_appoint && !requiredFields.cus_mobile) {
				return callback();
			}
			if (!this.isEditMobile) {
				return callback();
			}
			if (!value) {
				return callback(new Error("请填写手机号"));
			}
			if (!validate.mobile.test(value)) {
				return callback(new Error("客户手机号格式不正确"));
			}
			return callback();
		};
		// const isCusWxValidator = msg => {
		// 	return (rule, value, callback) => {
		// 		const { cus_wx } = this.form;
		// 		if (!cus_wx) {
		// 			return callback();
		// 		}
		// 		if (!value) {
		// 			return callback(new Error(msg));
		// 		}
		// 		return callback();
		// 	};
		// };
		const validateWx = (rule, value, callback) => {
			if (!this.isEditWx) {
				return callback();
			}
			let len = value.length;
			// if (len < 6 || len > 20) {
			// 	return callback(new Error("微信号6-20个字数"));
			// }
			// if (!validate.wechat.test(value)) {
			// 	return callback(new Error("格式为字母、下划线或减号，以字母开头"));
			// }
			return callback();
		};
		return {
			enterpriseWxList: [],
			form: {
				cus_id: "",
				id_join_type: "",
				addWechatNumber: "",
				biz_id: "",
				cus_type: 0,
				first_shop: "",
				to_shop: "",
				// company_id: "",
				bra_id: "",
				cus_name: "",
				cus_mobile: "",
				cus_wx: "",
				cus_sex: 2,
				wechat_join_day: "",
				source_id: "",
				has_appoint: 0,
				from_cus_id: ""
			},
			rules: {
				biz_id: [{ required: true, message: "请选择事业部" }],
				from_cus_id: [{ required: true, message: "请选填写介绍人会员号" }],
				company_id: [{ required: true, message: "请选择分公司" }],
				bra_id: [{ required: true, message: "请选择品牌" }],
				cus_type: [{ required: true, message: "请选择是否是老客户" }],
				first_shop: [{ required: true, message: "请选择到店时间" }],
				to_shop: [{ required: true, message: "请填写到店次数" }],
				cus_name: [{ required: true, message: "请填写客户名" }],
				cus_mobile: [{ validator: mobileValidator }],
				cus_wx: [
					{ required: true, message: "请填写客户微信号" },
					{ validator: validateWx }
				],
				wechat_join_day: [{ required: true, message: "请选择加微时间" }],
				id_join_type: [{ required: true, message: "请选择加微方式" }],
				addWechatNumber: [{ required: true, message: "请选择企业微信码" }],
				source_id: [
					{ required: true, message: "请选择来源渠道" }
					// { validator: isCusWxValidator("请选择来源渠道") }
				]
			},
			// 分公司
			companyList: [],
			// 品牌列表
			brandList: [],
			// 门店列表
			shopList: [],
			sourceList: [],
			pickerOptions: {
				disabledDate(time) {
					let now = dayjs();
					let date = dayjs(time);
					return date.isAfter(now);
					return date.isBefore(now.subtract(30, "day")) || date.isAfter(now);
				}
			},
			saving: false,
			//是否重粉
			haveFan: false,
			detail: {},
			args: {
				// 禁用字段
				disabled: [],
				hide: [],
				required: [],
				// 提交成功回调方法
				callback: null,
				form: {}
			}
		};
	},
	computed: {
		//事业部
		isEditMobile() {
			return this.detail.cus_mobile !== this.form.cus_mobile;
		},
		isEditWx() {
			return this.detail.cus_wx !== this.form.cus_wx;
		},
		bizRefData() {
			const { biz_id } = this.form;
			return this.getBizRefData(biz_id);
		},
		hideFields() {
			let { hide } = this.args;
			if (!hide) return {};
			return hide.reduce((prev, curr) => {
				return {
					...prev,
					[curr]: true
				};
			}, {});
		},
		requiredFields() {
			let { required } = this.args;
			let fields = {};
			Object.entries(this.rules).forEach(([k, r]) => {
				if (r[0].required) {
					fields[k] = true;
				}
			});
			if (!required) return fields;
			return required.reduce((prev, curr) => {
				return {
					...prev,
					[curr]: true
				};
			}, fields);
		}
	},
	created() {
		this.form.biz_id = this.getCurrBiz();
	},
	methods: {
		open(data = {}, args = {}) {
			this.args = args;
			const { haveFan } = args;
			console.log(haveFan, data, "====");
			this.$store.commit("common/SET_CUS_FORM_SUBMIT", false);
			this.$refs.drawer.create();
			this.haveFan = haveFan ?? false;
			// if (haveFan) {
			this.detail = data;
			Object.keys(this.form).forEach(key => {
				data[key] != undefined && (this.form[key] = data[key]);
			});
			// }
			if (haveFan) {
				this.form.has_appoint = 0;
				this.form.cus_type = 0;
			}
			let date = dayjs().format("YYYY-MM-DD");
			this.form.wechat_join_day = date;
			this.getBizRelation();
			this.getEnterpriseWx();
		},
		close() {
			this.reset();

			// console.info("小城", this.$refs);
			this.$refs.drawer.close();
		},
		reset() {
			this.$refs.form.resetFields();
			this.$resetFields(this.form);
			this.form = {
				...this.form,
				biz_id: this.getCurrBiz(),
				cus_type: 0,
				cus_sex: 2,
				has_appoint: 0
			};
		},
		submit() {
			this.$refs.form.validate(async (valid, errors) => {
				this.showFormErr(errors);
				if (!valid) return;

				const { ...args } = this.form;
				this.saving = true;
				let form = {
					...args,
					...this.args.form
				};

				delete form.cus_id;
				const { callback } = this.args;
				form.firstShops = form.firstShop;
				form.wechatJoinDays = form.wechatJoinDay;
				delete form.wechatJoinDay;
				delete form.firstShop;
				try {
					await this.$service.customer
						.add(form)
						.then(res => {
							console.log("新增客户", res);
							this.$emit("success", res);
						})
						.done(() => {
							this.saving = false;
						});
					callback && callback();
					setTimeout(() => {
						this.$store.commit("common/SET_CUS_FORM_SUBMIT", true);
						this.$message.success("操作成功");
						this.close();
					}, 50);
				} catch (error) {
					if (!error.cus_id) return false;
					callback && callback();
					setTimeout(() => {
						this.$store.commit("common/SET_CUS_FORM_SUBMIT", true);
						// this.$message.success("新增重粉成功");
						const h = this.$createElement;
						this.$msgbox({
							title: "提示",
							message: h("p", null, [
								h(
									"p",
									{ style: "color: rgb(250, 51, 84); font-size: 20px" },
									"重粉了！已为你创建重粉客户！"
								),
								h(
									"p",
									null,
									`刚新增的客户和“${error.dept_name}”-“${error.belonger}”的客户重粉了！`
								)
							]),
							customClass: "have-fan-confirm",
							closeOnClickModal: false,
							showCancelButton: false,
							confirmButtonText: "关闭",
							type: "warning",
							callback: () => {
								this.close();
							}
						});

						// this.$confirm(`刚新增的客户和“${error.dept_name}”-“${error.belonger}”的客户重粉了！`, "提示", {
						// 	confirmButtonText: "关闭",
						// 	// cancelButtonText: "取消",
						// 	customClass: 'have-fan-confirm',
						// 	showCancelButton: false,
						// 	closeOnClickModal: false,
						// 	type: "warning"
						// }).then(() => {
						// 	// this.open(error, {
						// 	// 	haveFan: true
						// 	// });
						// });
						// this.close();
					}, 50);
					// this.$confirm("该用户是重粉客户, 是否去新增重粉客户?", "提示", {
					// 	confirmButtonText: "确定",
					// 	cancelButtonText: "取消",
					// 	closeOnClickModal: false,
					// 	type: "warning"
					// }).then(() => {
					// 	this.open(error, {
					// 		haveFan: true
					// 	});
					// });
				}
			});
		},
		validField(field) {
			this.$refs.form.validateField(field);
		},
		changeBiz() {
			// this.form.company_id = "";
			this.form.bra_id = "";
			this.form.source_id = "";
			this.$refs.brand.resetField();
			this.getBizRelation();
			this.getEnterpriseWx();
		},
		changeBra() {},
		getBizRelation() {
			// this.getBizRefCompany(biz_id);
			this.getBrand();

			this.getSource();
		},
		cusWxChange(v) {
			!v && this.$refs.wechatJoinDay.resetField();
		},

		//获取来源渠道
		async getSource() {
			const { biz_id } = this.form;
			this.sourceList = [];
			if (!biz_id) return;
			const data = await this.$service.source.list({ biz_id, type: 2, status: 1 });
			this.sourceList = data;
		},
		//获取品牌
		async getBrand() {
			const { biz_id } = this.form;
			const data = await this.getBizRefBrand(biz_id);
			this.form.bra_id = data.length == 1 ? data[0]?.bra_id ?? "" : "";
		},
		//获取企业微信
		getEnterpriseWx() {
			const { biz_id } = this.form;
			this.$service.customer.getEnterpriseWx({ biz_id }).then(data => {
				let list = (data || []).map(v => ({ ...v, label: v.content, value: v.id }));
				this.enterpriseWxList = list;
				if (this.enterpriseWxList.length === 1) {
					this.form.addWechatNumber = this.enterpriseWxList[0].label;
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.tips {
	color: #aaa;
	font-size: 12px;
}
::v-deep {
	.el-col .el-form-item {
		min-height: 60px !important;
	}
}
.tag-wrap {
	width: 100%;
	height: 60px;
	::v-deep {
		.el-select__tags {
			top: 28%;
		}
		.el-input {
			height: 100%;
			background-color: #ffffff;
			border-radius: 4px;
			border: 1px solid #dcdfe6;
			&__inner {
				height: 28px !important;
				border: none;
			}
		}
	}
}
</style>
